# -*- coding: utf-8 -*-
import logging
import time

from mon.baselib.utils import OsUtils, TimeUtils

from src.handler.AbstractHandler import AbstractHandler
from src.handler.hongbao import HongBaoConfig
from src.handler.hongbao.TecentJiXuXinShangProcess import TecentJiXuXinShangProcess
from src.handler.hongbao.TecentQiangHongBaoProcess import TecentQiangHongBaoProcess


class TecentGuoFuTaskHandler(AbstractHandler):
    def _setup_arg(self, subparsers):
        # 添加关闭计算机的子命令
        parser_hong_bao = subparsers.add_parser('hb2', help='抢红包')
        parser_hong_bao.add_argument('--minute', '-m', type=int, default=30, help='Countdown in seconds before shutdown (default: 30)')
        parser_hong_bao.add_argument('--number', '-n', type=int, default=50, help='number of hong bao')
        parser_hong_bao.set_defaults(func=self.do_process)

    def _check(self, args):
        """检查参数是否有效"""
        return True

    def _process(self, args):
        HongBaoConfig.create_default_config_file()
        config_params = HongBaoConfig.get_config_params()
        finish_lock_str = config_params.get("finish_lock")
        finish_close_str = config_params.get("finish_close")

        start_time = time.time()
        run_duration = args.minute * 60
        num = 0

        tecent_qiang_hong_bao = TecentQiangHongBaoProcess(self.config, config_params)
        tecent_qiang_hong_bao.process()
        while (time.time() - start_time < run_duration) and (num < args.number):
            TimeUtils.wait_for_seconds(15, "等待广告", "广告结束")
            ji_xu_xin_shang = TecentJiXuXinShangProcess(self.config, config_params)
            result = ji_xu_xin_shang.process()
            if result:
                num += 1
                logging.info(f"==========已抢红包个数: {num} 耗时：{(time.time() - start_time) / 60}==========")

        if HongBaoConfig.str_to_bool(finish_lock_str):
            OsUtils.lock_screen(3)
        if HongBaoConfig.str_to_bool(finish_close_str):
            OsUtils.shutdown(30)
